package fr.mhz;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;

import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;

public class Main {

	public static void main(String[] args) {
		// CLI
		final Options options = new Options();
		options.addOption("f", true, "Radar folder to aggregate");

		final CommandLineParser parser = new PosixParser();
		CommandLine line = null;
		try {
			line = parser.parse(options, args);
		} catch (ParseException exp) {
			exp.printStackTrace();
		}

		if (line.hasOption("f") && line.getOptionValue("f") != null) {
			String folder = line.getOptionValue("f");
			System.out.println(folder);

			File folderFile = new File(folder);
			File[] files = folderFile.listFiles();

			CSVWriter writer = null;
			try {
				writer = new CSVWriter(new FileWriter(folder + "\\radars.csv"));
				for (File file : files) {
					readFileAndAggregate(file.getAbsolutePath(), writer);
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (writer != null)
					try {
						writer.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
			}
		} else {
			HelpFormatter hf = new HelpFormatter();
			hf.printHelp("Radar aggregator", options);
			return;
		}
	}

	public static void readFileAndAggregate(String path, CSVWriter writer) {
		CSVReader reader;

		try {
			reader = new CSVReader(new FileReader(path));
			String[] nextLine = null;
			String[] updatedLine = null;
			while ((nextLine = reader.readNext()) != null) {
				updatedLine = new String[5];
				updatedLine[0] = getRadarType(path);
				updatedLine[1] = getRadarSpeed(path);
				updatedLine[2] = nextLine[0];
				updatedLine[3] = nextLine[1];
				updatedLine[4] = getRadarSens(nextLine[2]);
				writer.writeNext(updatedLine);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static String getRadarType(String path) {
		String name = FilenameUtils.getBaseName(path);
		String[] result = name.split("-");
		if (result != null && result.length >= 1) {
			return result[0];
		}
		return StringUtils.EMPTY;
	}

	public static String getRadarSpeed(String path) {
		String name = FilenameUtils.getBaseName(path);
		String[] result = name.split("-");
		if (result != null && result.length >= 2) {
			return String.valueOf(Integer.valueOf(result[1]));
		}
		return StringUtils.EMPTY;
	}

	public static String getRadarSens(String radarCode) {
		String[] result = radarCode.split("_");
		if (result != null && result.length >= 3) {
			return result[result.length - 1];
		}
		return StringUtils.EMPTY;
	}
}
